import appApi from '@/apis/app'
import userApi from '@/apis/user'
import Cookies from 'js-cookie'

const uid = Cookies.get('DP_UID')

const types = {
  APP_INIT: 'APP_INIT',
  LOGGED_IN: 'LOGGED_IN',
  LOG_OUT: 'LOG_OUT'
}

const state = {
  ready: false,
  logged_in: uid && uid > 0
}

const actions = {
  login ({ commit }) {
    commit(types.LOGGED_IN)
  },
  async logout ({ commit }) {
    await userApi.logout()
    commit(types.LOG_OUT)
    location.reload()
  },
  async init ({ commit, state }) {
    const data = await appApi.getSession()
    commit(types.APP_INIT, data)
  }
}

const mutations = {
  [types.LOGGED_IN] (state) {
    state.logged_in = true
  },
  [types.LOG_OUT] (state) {
    state.logged_in = false
    state.ready = false
    delete state.info
    delete state.user
  },
  [types.APP_INIT] (state, payload) {
    // const newState = {
    //   ...state,
    //   ...payload.info,
    //   ready: true,
    //   user: payload.user
    // }
    // state = newState
    state.ready = true
    state.id = payload.info.id
    state.info = payload.info
    state.user = payload.user
  }
}

export default {
  state,
  actions,
  mutations
}
